package com.smsVerification.service.test;

import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.asymmetric.KeyType;
import cn.hutool.crypto.asymmetric.RSA;
import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.smsVerification.config.HttpCode;
import com.smsVerification.pojo.CommonResult;
import com.smsVerification.pojo.UserAuthVO;
import com.smsVerification.service.captcha.ICaptchaInfoService;
import com.smsVerification.service.login.ILoginService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
@Slf4j
@RefreshScope
public class LoginServiceTestImpl {

    /**
     * 极光开发APP KEY
     */
    @Value("${jiguang.jpush.app-key}")
    String JPUSH_APP_KEY;

    /**
     * 极光开发MASTER SECRET
     */
    @Value("${jiguang.jpush.master-secret}")
    String JPUSH_MASTER_SECRET;

    /**
     * 极光的公钥 （用于一键登录加密手机号码）
     */
    @Value("${jiguang.jverify.public-key}")
    String JVERIFY_PUBLIC_KEY;

    /**
     * 极光的私钥 (用于一键登录加密手机号码)
     */
    @Value("${jiguang.jverify.private-key}")
    String JVERIFY_PRIVATE_KEY;

    @Resource
    CaptchaInfoServiceTestImpl captchaInfoServiceTest;

    /**
     * 验证码登录
     *
     * @param phoneNumber 电话号码
     * @param captcha     验证码
     * @return 用户信息
     */
    public CommonResult<UserAuthVO> loginByCaptcha(String phoneNumber, int captcha) {
        //判断验证码是否正确
        CommonResult<Boolean> verifyResult = captchaInfoServiceTest.checkCaptcha(captcha, phoneNumber);

        //判断验证码是否正确
        if (verifyResult.getData() == null || !verifyResult.getData()) {
            return new CommonResult<>(HttpCode.WRONG_PARAM, "认证失败", new UserAuthVO(false, null));
        }

        //登陆成功，通过电话号码获取用户信息
        UserAuthVO userAuthVO = getUserInfoByPhoneNumber(phoneNumber);
        return new CommonResult<>(HttpCode.SUCCESS, "成功", userAuthVO);
    }

    /**
     * 一键登录
     *
     * @param loginToken 极光认证一键登录的秘钥
     * @return 用户信息
     */
    public CommonResult<UserAuthVO> loginByJverify(String loginToken) {
        //获取登录成功后解密过后的电话号码
        String phoneNumber = getPhoneByJVerify(loginToken);

        //如果是NULL说明是登录失败
        if (phoneNumber == null) {
            return new CommonResult<>(HttpCode.WRONG_PARAM, "认证失败", new UserAuthVO(false, null));
        }

        //登陆成功，通过电话号码获取用户信息
        UserAuthVO userAuthVO = getUserInfoByPhoneNumber(phoneNumber);

        return new CommonResult<>(HttpCode.SUCCESS, "成功", userAuthVO);

    }

    /**
     * 一键登录，获取登录成功后解密过后的电话号码
     */
    private String getPhoneByJVerify(String loginToken) {

        JSONObject param = new JSONObject();
        param.put("loginToken", loginToken);

        String result = HttpRequest.post("https://api.verification.jpush.cn/v1/web/loginTokenVerify")
                .basicAuth(JPUSH_APP_KEY, JPUSH_MASTER_SECRET)
                .body(param.toString())
                .timeout(20000)
                .execute().body();

        JSONObject jsonObject = JSON.parseObject(result);

        //加密后的电话号码（RSA加密）
        String phoneToken = jsonObject.getString("phone");

        //返回解密后的电话号码（通过私钥解密）
        if (phoneToken != null) {
            RSA rsa = new RSA(JVERIFY_PRIVATE_KEY, JVERIFY_PUBLIC_KEY);
            byte[] decrypt = rsa.decrypt(phoneToken, KeyType.PrivateKey);

            return StrUtil.str(decrypt, CharsetUtil.CHARSET_UTF_8);
        } else {
            return null;
        }

    }

    /**
     * 通过电话号码获取用户信息
     */
    private UserAuthVO getUserInfoByPhoneNumber(String phoneNumber) {
        //通过电话号码获取用户的身份信息
        // ...
        return null;
    }


}
